//////////////////////////////////////////////////////////////////////////////////
//                                                                              //
//  This file is part of the buola project (https://code.google.com/p/buola/).  //
//                                                                              //
//  Copyright(c) 2007-2012 Xavi Gratal                                          //
//  gratal AT gmail DOT com                                                     //
//                                                                              //
//  Buola is free software: you can redistribute it and/or modify               //
//  it under the terms of the GNU General Public License as published by        //
//  the Free Software Foundation, either version 3 of the License, or           //
//  (at your option) any later version.                                         //
//                                                                              //
//  Buola is distributed in the hope that it will be useful,                    //
//  but WITHOUT ANY WARRANTY; without even the implied warranty of              //
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the               //
//  GNU General Public License for more details.                                //
//                                                                              //
//  You should have received a copy of the GNU General Public License           //
//  along with buola.  If not, see <http://www.gnu.org/licenses/>.              //
//                                                                              //
//////////////////////////////////////////////////////////////////////////////////

#include <buola/io/cfdstream.h>

#include <fcntl.h>       // file opening flags.
#include <sys/stat.h>    // file access permissions.
#include <unistd.h>     // low-level file i/o.
#include <buola/io/cfdpoller.h>
#include <buola/io/ctextreader.h>
#include <buola/io/ctextwriter.h>
#include <buola/io/cindirectbufferstream.h>

namespace buola { namespace io {

CFDStream::CFDStream(int pFD, bool pCloseOnExit)
    :   mFD(pFD)
    ,   mCloseOnExit(pCloseOnExit)
{

}

CFDStream::~CFDStream()
{
    if(mFD>=0&&mCloseOnExit)
        Close();
    get_main_fd_poller().RemoveFDListeners(this);
}

CResult CFDStream::Read(uint8_t *pData, size_t pLen)
{
    errno = 0;
    ssize_t lRead=::read(mFD,pData,pLen);

    if(lRead>0)
        return CResult(lRead);
    if(lRead==0)
        return CResult(0,EResult::ENDOFFILE);

    switch(errno)
    {
    case EINTR:
        return Read(pData,pLen);
    case EAGAIN:
#if EAGAIN!=EWOULDBLOCK
    case EWOULDBLOCK:
#endif
        return CResult(0,EResult::WOULDBLOCK);
    case EFAULT:
        throw XMemory(I18N("Segmentation fault"));
    case EIO:
        throw XHardware(I18N("I/O error"));
    case EINVAL:
    case EBADF:
        throw XInternal(I18N("Invalid descriptor"));
    case EISDIR:
        throw XMismatch(I18N("Is a directory"));
    default:
        throw XInternal(I18N("Unexpected read error"));
    }
}

CResult CFDStream::Write(const uint8_t *pData, size_t pLen)
{
    ssize_t lWritten=::write(mFD,pData,pLen);

    if(lWritten==pLen)
        return CResult(pLen);
    
    if(lWritten>=0)
    {
        CResult lRetry=Write(pData+lWritten,pLen-lWritten);
        return CResult(lWritten+lRetry.Count(),lRetry.Flags());
    }

    switch(errno)
    {
    case EINTR:
        return Write(pData,pLen);
    case EAGAIN:
#if EAGAIN!=EWOULDBLOCK
    case EWOULDBLOCK:
#endif
        return CResult(0,EResult::WOULDBLOCK);
    case EFAULT:
        throw XMemory(I18N("Segmentation fault"));
    case EIO:
        throw XHardware(I18N("I/O error"));
    case EINVAL:
    case EBADF:
        throw XInternal(I18N("Invalid descriptor"));
    case EISDIR:
        throw XMismatch(I18N("Is a directory"));
    case EDQUOT:
        throw XFull(I18N("Disk quota surpassed"));
    case EFBIG:
        throw XFull(I18N("File too big"));
    case ENOSPC:
        throw XFull(I18N("Disk full"));
    case EPIPE:
        throw XFull(I18N("Broken pipe"));
    default:
        throw XInternal(I18N("Unexpected read error"));
    }
}

off_t CFDStream::Seek(off_t pPos, ESeek pMode)
{
    off_t lOffset=lseek(mFD,pPos,pMode==ESeek::ABSOLUTE?SEEK_SET:(pMode==ESeek::RELATIVE?SEEK_CUR:SEEK_END));

    if(lOffset>=0)
        return lOffset;

    switch(errno)
    {
    case EINVAL:
    case EBADF:
        throw XInternal(I18N("Invalid descriptor"));
    case EOVERFLOW:
        throw XInvalid(I18N("Invalid seek offset"));
    case ESPIPE:
        throw XMismatch(I18N("Stream is not seekable"));
    default:
        throw XInternal(I18N("Unexpected seek error"));
    }
}

void CFDStream::Close()
{
    if(mFD<0) return;

    if(::close(mFD)<0)
        throw XInternal(I18N("Unexpected close error"));
    
    mFD=-1;
}

void CFDStream::SetActivityDelegate(DStreamActivity *pDelegate,ENotify pNotify)
{
    mActivityDelegate=pDelegate;
    
    if(mActivityDelegate)
        get_main_fd_poller().AddFDListener(this,mFD,pNotify);
    else
        get_main_fd_poller().RemoveFDListeners(this);
}

inline static int parse_open_mode(EMode pMode)
{
    int lFlags=0;

    switch((EMode)(pMode&EMode::OPENORCREATE))
    {
    case EMode::OPEN:
        break;
    case EMode::CREATE:
        lFlags|=O_CREAT|O_EXCL;
        break;
    case EMode::OPENORCREATE:
    default:
        lFlags|=O_CREAT;
        break;
    }
    
    switch((EMode)(pMode&EMode::READWRITE))
    {
    case EMode::READ:
        lFlags|=O_RDONLY;
        break;
    case EMode::WRITE:
        lFlags|=O_WRONLY;
        break;
    case EMode::READWRITE:
        lFlags|=O_RDWR;
        break;
    default:
        throw XArgument("wrong open mode");
    }

    if((pMode&EMode::APPEND)==EMode::APPEND)
        lFlags|=O_APPEND;

    if((pMode&EMode::TRUNCATE)==EMode::TRUNCATE)
        lFlags|=O_TRUNC;

    if(pMode&EMode::SYNC)
        lFlags|=O_SYNC;

    if(pMode&EMode::NONBLOCK)
        lFlags|=O_NONBLOCK;

    return lFlags;
}

PFDStream open_disk_file(const std::string &pPath,EMode pMode,EPermission pPerm)
{
    int lFlags=parse_open_mode(pMode);

    int lFD=::open(pPath.c_str(),lFlags,pPerm);

    if(lFD<0)
    {
        switch(errno)
        {
        case EEXIST:
            throw XAlready(I18N("File already exists"));
        case EACCES:
        case EROFS:
        case ETXTBSY:
            throw XPermission(I18N("Requested access to file not allowed"));
        case ENAMETOOLONG:
            throw XArgument(I18N("Object has wrong name"));
        case EISDIR:
        case ENOENT:
        case ENOTDIR:
            throw XNotFound(pPath+I18N(": File not found or is a directory"));
        case ENXIO:
        case ENODEV:
            throw XConnection(I18N("No one there"));
        case EFAULT:
            throw XMemory(I18N("Segmentation fault"));
        case ENOMEM:
            throw XMemory(I18N("Out of memory"));
        case ENOSPC:
            throw XFull(I18N("Device is full"));
        case ENFILE:
        case EMFILE:
            throw XFull(I18N("Too many files"));
#if PLATFORM_BUOLA_LINUX
        case ENOMEDIUM:
            throw XNotFound(I18N("No medium"));
#endif //PLATFORM_BUOLA_LINUX
        default:
            throw XInternal(I18N("Unexpected error during open"));
        }
    }

    return new CFDStream(lFD);
}

void CFDStream::OnFDListener(int pFD,ENotify pEvent,void *pUserPtr)
{
    if(mActivityDelegate)
    {
        if(pEvent&ENotify::READ)
            mActivityDelegate->OnStreamCanRead(this);
        if(pEvent&ENotify::WRITE)
            mActivityDelegate->OnStreamCanWrite(this);
        if(pEvent&ENotify::EXCEPTION)
            mActivityDelegate->OnStreamException(this);
    }
}

/*namespace io*/ } 

///\todo set flush on newline only if it's a terminal
io::CTextReader gIn(new io::CIndirectBufferStream(new io::CFDStream(STDIN_FILENO,false)));
io::CTextWriter gOut(new io::CIndirectBufferStream(new io::CFDStream(STDOUT_FILENO,false)),true);
io::CTextWriter gErr(new io::CIndirectBufferStream(new io::CFDStream(STDERR_FILENO,false)),true);

/*namespace buola*/ }
